//
//  BIZConsultorPersonalDetailVC.m
//  biz
//
//  Created by zhangfuwei on 2017/4/11.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZConsultorPersonalDetailVC.h"
#import "BIZConsultEditViewController.h"
#import "BIZRapidConsultResultVC.h"
#import "BIZOfflineConsultQuestionVC.h"
#import "BIZContractEditVC.h"

// cell
#import "BIZConsultorIntroductionCell.h"
#import "BIZConsultorImagesTabCell.h"
#import "BIZConsultorHeadTabCell.h"
#import "BIZPositionSkillCell.h"

// model
#import "BIZConsultorDetailModel.h"
#import "BIZConsultorListDataModel.h"

#import "MXNavigationBarManager.h"

static NSString *const kHeadCellID = @"kHeadCellID";
static NSString *const kPositionSkillCellID = @"kPositionSkillCellID";
static NSString *const kImagesCellID = @"kImagesCellID";
static NSString *const kIntroductionCellID = @"kIntroductionCellID";
static CGFloat kConsultorButtonH = 55;
@interface BIZConsultorPersonalDetailVC ()<UITableViewDelegate,UITableViewDataSource>
/** tableView */
@property (nonatomic, strong) UITableView *tableView;

/** */
@property (nonatomic, strong) UIButton *consultButton;

@property (nonatomic, strong) BIZConsultorDetailModel *detailM;

/** 是否是线下咨询 */
@property (nonatomic, assign) BIZConsultorPersonalDetailVCTypeFrom typeFrom;

/** 专题,税种,行业 选择的 标签 */
@property (nonatomic, assign) NSInteger positionSkillCellSelectedIdx;


@end

@implementation BIZConsultorPersonalDetailVC

- (instancetype)initWithTypeFrom:(BIZConsultorPersonalDetailVCTypeFrom)typeFrom
{
    self = [super init];
    if (self) {
        _typeFrom = typeFrom;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.positionSkillCellSelectedIdx = 0;
    [self loadUI];
    [self getDetailInfoWithConsultorId:self.dataM.uuid];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self initBarManager];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tableView.delegate = nil;
    self.automaticallyAdjustsScrollViewInsets = YES;
    [MXNavigationBarManager reStoreToSystemNavigationBar];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initBarManager {
    [MXNavigationBarManager managerWithController:self];
    [MXNavigationBarManager setBarColor:COLOR_NAVBAR_BLUE];
    [MXNavigationBarManager setTintColor:[UIColor colorWithRed:0.15 green:0.15 blue:0.15 alpha:1]];
    [MXNavigationBarManager setStatusBarStyle:UIStatusBarStyleDefault];
    [MXNavigationBarManager setZeroAlphaOffset:0];
    [MXNavigationBarManager setFullAlphaOffset:200];
    [MXNavigationBarManager setFullAlphaTintColor:[UIColor whiteColor]];
    [MXNavigationBarManager setFullAlphaBarStyle:UIStatusBarStyleLightContent];
}

- (void)loadUI {

    [self.view addSubview:self.tableView];
    [self.view addSubview:self.consultButton];

    NSString    *title ;
    UIColor     *bgColor;
    switch (_typeFrom) {
        case BIZConsultorPersonalDetailVCTypeFromHome:
            title   = @"咨询";
            bgColor = HEXCOLOR(0xfa6a31);
            break;
            
        case BIZConsultorPersonalDetailVCTypeFromOffline:
            title = @"选TA服务";
            bgColor = COLOR_NAVBAR_BLUE;

            break;
            
        case BIZConsultorPersonalDetailVCTypeFromContract:
            title = @"让TA审";
            bgColor = COLOR_NAVBAR_BLUE;

            break;
            
        default:
            break;
    }

    self.consultButton.backgroundColor = bgColor;
    [self.consultButton setTitle:title forState:UIControlStateNormal];
    
}

// app/cuser/home

#pragma mark -- 请求咨询师详情
- (void)getDetailInfoWithConsultorId:(NSString *)Id {
    
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kConsultorDetailInfo
           parameters:@{@"uuid":Id?:@""}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  [MBProgressHUD hideHUD];
                  DeLog(@"咨询师详情--%@",responseObject);
                  NSDictionary *dataDic = responseObject[@"data"];
                  int code = [responseObject[@"code"] intValue];
                  if (code == 1) {
                      
                      self.detailM = [BIZConsultorDetailModel yy_modelWithDictionary:dataDic];
            
                      [self.tableView reloadData];
                  } else if (code == 2) {
                     [MBProgressHUD showErrorMessage:responseObject[@"des"]];
                  } else {
                      [MBProgressHUD showErrorMessage:responseObject[@"des"]];
                  }

                  [self.tableView reloadData];
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"error ---%@",error);
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }

                  
              }
     ];
    
}

#pragma mark -- 数据源,代理


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row==0) {
        BIZConsultorHeadTabCell *cell = [tableView dequeueReusableCellWithIdentifier:kHeadCellID forIndexPath:indexPath];
        cell.detailM = self.detailM;
        return cell;

    }else if (indexPath.row==1){
        MJWeakSelf;
        BIZPositionSkillCell *cell = [tableView dequeueReusableCellWithIdentifier:kPositionSkillCellID forIndexPath:indexPath];
        cell.selectedIdx = _positionSkillCellSelectedIdx;
        cell.detailM = self.detailM;
        cell.switchBlock = ^(NSInteger idx){
            _positionSkillCellSelectedIdx = idx;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationNone];
        };
        return cell;
        
    }else if (indexPath.row== 2){
        BIZConsultorImagesTabCell *cell = [tableView dequeueReusableCellWithIdentifier:kImagesCellID forIndexPath:indexPath];
        cell.detailM = self.detailM;

        return cell;

    }else if (indexPath.row== 3){
        BIZConsultorIntroductionCell *cell = [tableView dequeueReusableCellWithIdentifier:kIntroductionCellID forIndexPath:indexPath];
        cell.detailM = self.detailM;

        return cell;

    }else {
        return nil;
    }
    
}

#pragma mark -- 私有方法
- (void)consultButtonClick:(UIButton *)btn {
    if (_typeFrom == BIZConsultorPersonalDetailVCTypeFromOffline) {
        
        //  跳转回问题咨询界面
        __block BIZOfflineConsultQuestionVC *questionVC ;
        MJWeakSelf;
        [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController *vc, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([vc isKindOfClass:[BIZOfflineConsultQuestionVC class]]) {
                questionVC = (BIZOfflineConsultQuestionVC *)vc;
                questionVC.dataM = weakSelf.dataM;
                [weakSelf.navigationController popToViewController:questionVC animated:YES];
                
                *stop = YES;
            }
            
        }];
        
        questionVC?: [MBProgressHUD showErrorMessage:@"要跳转的界面消失啦"];
        
    }else if (_typeFrom == BIZConsultorPersonalDetailVCTypeFromHome){
        MJWeakSelf;
        BIZConsultEditViewController *bizEdit = [[BIZConsultEditViewController alloc] initWithType:BIZConsultEditTypeOne2One cuserId:self.dataM.uuid finishBlock:^(BIZConsultQModel *model) {
            
            BIZRapidConsultResultVC *vc = [[BIZRapidConsultResultVC alloc] init];
            vc.alertTitleStr = @"您的问题已提交，请耐心等待咨询师回复";
            vc.questionModel =(BIZQuestionModel*)model;
            //        vc.questionModel.name = [BIZUserModel shareUser].name;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        
        BIZNavigationController *nav = [[BIZNavigationController alloc] initWithRootViewController:bizEdit];
        [self presentViewController:nav animated:YES completion:nil];
    }else if (_typeFrom == BIZConsultorPersonalDetailVCTypeFromContract){
        
//        BIZConsultEditViewController *bizEdit = [[BIZConsultEditViewController alloc] initWithType:BIZConsultEditTypeOne2One cuserId:self.dataM.uuid finishBlock:^(BIZConsultQModel *model) {
//            
//            BIZRapidConsultResultVC *vc = [[BIZRapidConsultResultVC alloc] init];
//            vc.alertTitleStr = @"您的问题已经提交，请耐心等待咨询师的回复，通常5分钟你会收到答案，请在“我的”中咨询列表中查看";
//            vc.questionModel =(BIZQuestionModel*)model;
//            //        vc.questionModel.name = [BIZUserModel shareUser].name;
//            [self.navigationController pushViewController:vc animated:YES];
//        }];
//        
//        BIZNavigationController *nav = [[BIZNavigationController alloc] initWithRootViewController:bizEdit];
//        [self presentViewController:nav animated:YES completion:nil];
        
        NSArray *arr = self.navigationController.viewControllers;
        for (UIViewController *vc in arr) {
            if ([vc isKindOfClass:[BIZContractEditVC class]]) {
                NSDictionary *dic = @{@"model":self.detailM};
                [[NSNotificationCenter defaultCenter] postNotificationName:kGetChooseConsultModelNotification object:nil userInfo:dic];
                [self.navigationController popToViewController:(BIZContractEditVC *)vc animated:YES];
                break;
            }
        }
        
        
    }

}

#pragma mark -- 懒加载

- (UITableView *)tableView {
    if (!_tableView) {
        CGRect tableViewFrame = CGRectMake(0, 0, Main_Screen_Width, self.view.bounds.size.height - kConsultorButtonH);
        _tableView = [[UITableView alloc] initWithFrame:tableViewFrame style:UITableViewStylePlain];
        
        [_tableView registerNib:[UINib nibWithNibName:@"BIZConsultorHeadTabCell" bundle:nil] forCellReuseIdentifier:kHeadCellID];
        [_tableView registerClass:[BIZPositionSkillCell class] forCellReuseIdentifier:kPositionSkillCellID];
        [_tableView registerClass:[BIZConsultorImagesTabCell class] forCellReuseIdentifier:kImagesCellID];
        [_tableView registerClass:[BIZConsultorIntroductionCell class] forCellReuseIdentifier:kIntroductionCellID];
        
        _tableView.backgroundColor = HEXCOLOR(0xEEEDEE);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        _tableView.tableFooterView = [UIView new];
        
        _tableView.estimatedRowHeight = 90;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        //    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
        //    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadConsultor)];

    }
    return _tableView;
}

- (UIButton *)consultButton {
    if (!_consultButton) {
        
        _consultButton = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - kConsultorButtonH, Main_Screen_Width, kConsultorButtonH)];
        
        [_consultButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_consultButton setTitleColor:COLOR_WORD_GRAY_1 forState:UIControlStateHighlighted];
        [_consultButton addTarget:self action:@selector(consultButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _consultButton.titleLabel.font = CHINESE_SYSTEM(16);
        
    }
    return _consultButton;
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    CGFloat reOffset = scrollView.contentOffset.y + (App_Frame_Height - 64) * 0.2;
//    CGFloat alpha = reOffset / ((App_Frame_Height - 64) * 0.2);
//    if (alpha <= 1){//下拉永不显示导航栏
//        
//        alpha = 0;
//        self.title = nil;
//
//    }else{//上划前一个导航栏的长度是渐变的
//        
//        alpha -= 1;
//        self.title = @"个人主页";
//    }
//    // 设置导航条的背景图片 其透明度随  alpha 值 而改变 JSBRGBColor(76, 92, 108)
//    UIImage *image = [self imageWithColor:[UIColor colorWithRed:46/255.0 green:140/255.0 blue:229/255.0 alpha:alpha]];
//    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
//}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [MXNavigationBarManager changeAlphaWithCurrentOffset:scrollView.contentOffset.y];
}

/// 使用颜色填充图片
- (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}


@end
